<?php
declare(strict_types=1);

namespace App\Helper;

use Hyperf\Utils\Arr;

class MenuHelper
{
    const TOP_MODULE = '管理后台';

    private $moduleWithSons = [];

    public function __construct(array $userModules)
    {
        foreach ($userModules as $userModule) {
            $module = explode('@', $userModule);
            $module = $module[0] ?? '';
            if (empty($module)) {
                continue;
            }
            $this->setModuleSon($module);
        }
    }

    private function setModuleSon(string $module): void
    {
        $moduleLites = explode(':', $module);
        array_pop($moduleLites);
        $moduleFather = implode(':', $moduleLites);
        if (!empty($moduleFather)) {
            key_exists($moduleFather, $this->moduleWithSons) || $this->moduleWithSons[$moduleFather] = [];
            if (!in_array($module, $this->moduleWithSons[$moduleFather], true)) {
                array_push($this->moduleWithSons[$moduleFather], $module);
            }
            $this->setModuleSon($moduleFather);
        }
    }

    public function getList(string $module = self::TOP_MODULE): array
    {
        $info = [];
        $modules = $this->moduleWithSons[$module] ?? [];
        foreach ($modules as $module) {
            $item = [
                'title' => Arr::last(explode(':', $module)),
                'href' => ModuleHelper::getHrefByModule($module),
                'icon' => ModuleHelper::getIconByModule($module),
                'target' => '_self',
                'child' => $this->getList($module),
            ];
            array_push($info, $item);
        }
        return $info;
    }
}

